<template>
    <div>
        <!-- 面包屑导肮 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card class="box-card">
            <el-button type="primary" @click="showAddDialog">添加角色</el-button>
            <el-table :data="rolesList" stripe border>
                <el-table-column type="expand">
                    <template #default="scope">
                        <el-row :class="['bdBottom',m1===0?'bdTop':'','vCenter']"
                            v-for="(menu,m1) in scope.row.children" :key="menu.id">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,menu.id)">{{menu.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row v-for="(per,p1) in menu.children" :key="per.id"
                                    :class="['bdBottom',m1===0?'bdTop':'','vCenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,per.id)">
                                            {{per.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag v-for="per2 in per.children" :key="per2.id" type="warning" closable
                                            @close="removeRightById(scope.row,per2.id)">{{per2.authName}}
                                        </el-tag>

                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" />
                <el-table-column label="角色名称" prop="roleName" width="300" />
                <el-table-column label="角色描述" prop="roleDesc" width="300" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" icon="el-icon-edit" size="small"
                            @click="showUpdateDialog(scope.row.id)">编辑
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="small"
                            @click="showSetRightDialog(scope.row)">分配权限
                        </el-button>

                        <el-button type="danger" icon="el-icon-delete" size="small"
                            @click="openDeleteBox(scope.row.id)">删除
                        </el-button>
                    </template>

                </el-table-column>

            </el-table>

        </el-card>
        <!-- 添加修改对话框 -->
        <el-dialog :title="this.addUpdateFormOper === 'add'?'添加角色':'修改角色'" :visible.sync="isShowDialog" width="30%">
            <span>
                <!-- 添加角色表单 -->
                <el-form label-width="85px" class="add_form" :model="addUpdateForm" :rules="addUpdateRules"
                    ref="addUpdateForm">
                    <!-- 角色名称 -->
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addUpdateForm.roleName" :disabled="addUpdateFormOper!=='add'"></el-input>
                    </el-form-item>
                    <!-- 描述 -->
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addUpdateForm.roleDesc"></el-input>
                    </el-form-item>

                </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogCancle">取 消</el-button>
                <el-button type="primary" @click="dialogOK">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="SetRightVisible" width="50%" @close="setRightDialogClose">
            <span>
                <el-tree ref="rightTree" :data="rightsList" :props="rightsProps" node-key="id"
                    :default-checked-keys="rightsKeys" accordion show-checkbox></el-tree>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="SetRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRight">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import {
    reqRolesList,
    reqRoleById,
    reqAddRole,
    reqUpdateRole,
    reqDeleteRoleById,
    reqDeleteRightById,
    reqRightList,
    reqSetRoleRight
} from '@/api'
export default {
    created() {
        //发送请求拿到用户列表
        this.getRolesList()
    },

    data() {
        return {
            rolesList: [],
            rightsList: [],
            isShowDialog: false,
            SetRightVisible: false,
            rightsProps: {
                label: 'authName',
                children: 'children'
            },
            rightsKeys: [],
            currentRoleId: '',
            addUpdateFormOper: 'add',
            addUpdateForm: {
                roleId: '',
                roleName: '',
                roleDesc: ''
            },
            addUpdateRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    },
                    {
                        min: 4,
                        max: 10,
                        message: '长度在 4 到 10 个字符',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
            }
        }
    },
    methods: {
        async getRolesList() {
            const {
                data,
                meta: { msg, status }
            } = await reqRolesList()
            if (200 !== status) return this.message.error(msg)
            this.rolesList = data
        },
        showAddDialog() {
            this.isShowDialog = true
            //打开后重新渲染dom 再选然后执行清空就不会报错了
            this.$nextTick(() => {
                this.$refs.addUpdateForm.resetFields()
            })
            this.addUpdateFormOper = 'add'
        },
        showUpdateDialog(id) {
            this.isShowDialog = true
            this.addUpdateFormOper = 'edit'
            this.getRoleById(id)
        },
        async showSetRightDialog(role) {
            const {
                data,
                meta: { msg, status }
            } = await reqRightList('tree')
            if (200 !== status) return this.$message.error(msg)
            this.rightsList = data
            this.currentRoleId = role.id
            this.getLeafKeys(role, this.rightsKeys)
            this.SetRightVisible = true
        },
        getLeafKeys(node, arr) {
            if (!node.children) return arr.push(node.id)
            node.children.forEach((nc) => {
                this.getLeafKeys(nc, arr)
            })
        },
        async setRight() {
            const { currentRoleId } = this

            let ridsArr = [
                ...this.$refs.rightTree.getHalfCheckedKeys(),
                ...this.$refs.rightTree.getCheckedKeys()
            ]
            let rids = ridsArr.join(',')
            const {
                meta: { msg, status }
            } = await reqSetRoleRight(currentRoleId, rids)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)
            this.getRolesList()
            this.SetRightVisible = false
        },
        setRightDialogClose() {
            this.rightsKeys = []
        },
        async getRoleById(id) {
            const {
                data,
                meta: { msg, status }
            } = await reqRoleById(id)
            if (200 !== status) return this.$message.error(msg)
            this.addUpdateForm = data
        },
        dialogCancle() {
            this.isShowDialog = false
            if (this.addUpdateFormOper !== 'add') return
            this.$refs.addUpdateForm.resetFields()
        },
        dialogOK() {
            this.$refs.addUpdateForm.validate(async (valid) => {
                // 验证有误
                if (!valid) return

                if (this.addUpdateFormOper === 'add') {
                    // 发送添加角色请求
                    const {
                        data,
                        meta: { msg, status }
                    } = await reqAddRole(this.addUpdateForm)
                    if (201 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getRolesList()
                    this.isShowDialog = false
                } else {
                    //发送修改角色请求
                    const { roleId, roleName, roleDesc } = this.addUpdateForm
                    const {
                        data,
                        meta: { msg, status }
                    } = await reqUpdateRole({ roleId, roleName, roleDesc })
                    if (200 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getRolesList()
                    this.isShowDialog = false
                }
            })
        },
        async deleteRole(id) {
            const {
                meta: { msg, status }
            } = await reqDeleteRoleById(id)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)

            this.getRolesList()
        },
        openDeleteBox(id) {
            this.$confirm('是否删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.deleteRole(id)
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },
        async removeRightById(role, rightId) {
            const confirmResult = await this.$confirm('确定要删除这个权限吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((err) => err)
            if (confirmResult !== 'confirm') return
            const {
                data,
                meta: { msg, status }
            } = await reqDeleteRightById(role.id, rightId)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)
            role.children = data
        }
    }
}
</script>
<style lang="less" scoped>
.el-tag {
    margin: 7px;
}
.bdTop {
    border-top: 1px solid #eee;
}
.bdBottom {
    border-bottom: 1px solid #eee;
}
.vCenter {
    display: flex;
    align-items: center;
}
</style>